<template>
  <div>
    <el-form :model="form" label-width="0.5rem" :rules="rules" ref="form">
      <!-- 题目创建 -->
      <el-form-item required label="题目" class="title" prop="title">
        <el-input
          type="text"
          v-on:click.native="createTitle"
          v-model="form.title"
          placeholder="请输入题目"
        >
        </el-input>
        <el-dialog title="题目" :visible.sync="createTitleVisible">
          <el-input
            ref="dialogInput"
            placeholder="请输入题目内容"
            type="textarea"
            v-model="anotherForm.title"
            rows="6"
          ></el-input>
          <div slot="footer">
            <el-button type="primary" @click.native="createTitleVisible = false"
              >取消</el-button
            >
            <el-button type="primary" @click.native="sureCreateTitle()"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>
      <!-- 选项 -->
      <el-form-item label="选项" required>
        <el-button
          icon="el-icon-circle-plus-outline"
          type="primary"
          size="mini"
          round
          @click="addAnswer()"
          >添加选项</el-button
        >
      </el-form-item>
      <!-- 选项ABCD -->
      <el-form-item
        :key="index"
        prop="answer"
        :label="item.prefix"
        v-for="(item, index) in form.answer"
        class="options"
      >
        <el-row>
          <el-col :span="23">
            <el-input
              type="text"
              v-on:click.native="
                createOptions(index, item.prefix, item.content)
              "
              v-model="item.content"
              placeholder="请输入选项内容"
            ></el-input>
          </el-col>
          <el-col :span="1">
            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="form.answer.splice(index, 1)"
            >
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-dialog
        :title="`选项_${anotherForm.answer.prefix}`"
        :visible.sync="createOptionsVisible"
        style="text-align: center"
      >
        <el-form label-width="80px">
          <el-form-item label="选项内容">
            <el-input
              type="textarea"
              v-model="anotherForm.answer.content"
              rows="6"
              ref="dialogInput"
              auto-complete="off"
              placeholder="请输入选项内容"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click.native="createOptionsVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click.native="sureCreateOptions()"
            >确定</el-button
          >
        </div>
      </el-dialog>
      <!-- 答案 -->
      <el-form-item label="答案" required prop="correct" class="answer">
        <el-radio-group v-model="form.correct">
          <el-radio-button
            v-for="item in form.answer"
            :key="item.prefix"
            :label="item.prefix"
          ></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- 难度-->
      <el-form-item label="难度">
        <el-select v-model="form.level" placeholder="请选择">
          <el-option
            v-for="item in anotherForm.level"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 知识点 -->
      <el-form-item prop="tags" required label="知识点">
        <el-tag
          :key="index"
          v-for="(item, index) in form.tags"
          closable
          :disable-transitions="false"
          @close="form.tags.splice(index, 1)"
        >
          {{ item.name }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput"
          >+ New Tag</el-button
        >
      </el-form-item>    
      <el-form-item>
        <el-button @click="resetForm" type="info" round class="cancel"
          >重置</el-button
        >
        <el-button type="primary" v-debounce="upload" round
          >提交<i class="el-icon-upload el-icon--right"> </i
        ></el-button>
        <el-dialog :visible.sync="UploadVisible">
          题目预览，是否提交
          <choice-detail :question="form"></choice-detail>
          <div slot="footer">
            <el-button @click.native="UploadVisible = false">取消</el-button>
            <el-button
              type="primary"
              :loading="submitLoading"
              v-debounce="retUpload"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { uploadSLProblem, editSLProblem } from "@/api/question";
import choiceDetail from "@/components/choiceDetail.vue";
export default {
  name: "choiceCreate",
  components: { choiceDetail },
  data() {
    var validateAnswer = (rule, value, callback) => {
      if (!value || value.length == 0) {
        callback(new Error("选项不能为空，请添加选项"));
      }
      value.forEach((element) => {
        if (element.content == null || element.content == "") {
          callback(new Error(`${element.prefix} 选项不能为空，如不需要请删除`));
        }
      });
      callback();
    };
    return {
      // 创建题目弹层
      createTitleVisible: false,
      // 创建选项弹层
      createOptionsVisible: false,
      inputVisible: false,
      inputValue: "",
      UploadVisible: false,
      submitLoading: false, //提交按钮加载中效果
      num: null,
      correct: null,
      isAdd: true, //添加还是编辑
      // 传给后端数据
      form: {
        // 题目
        title: null,
        // 选项
        answer: [
          { prefix: "A", content: null },
          { prefix: "B", content: null },
          { prefix: "C", content: null },
          { prefix: "D", content: null },
        ],
        // 答案
        correct: null,
        // 水平level "0"
        level: 1, //0表示Low 1表示Middle 2表示High
        type: 0,
        userId: null,
        tags: [],
      },
      // 临时数据
      anotherForm: {
        title: "",
        // 选项
        answer: {
          prefix: "",
          content: "",
        },
        // 答案
        correct: [],
        level: [
          { value: 0, label: "Low" },
          { value: 1, label: "Middle" },
          { value: 2, label: "High" },
        ],
        tags: [],
      },
      // 表单校验
      rules: {
        // 题目的校验
        title: [{ required: true, message: "请输入题目", trigger: "blur" }],
        // 选项的校验
        // 答案校验
        correct: [
          { required: true, message: "请选择一个答案", trigger: "change" },
        ],
        answer: [{ validator: validateAnswer, trigger: "blur" }],
      },
    };
  },
  created() {
    if (this.$route.params.data) {
      this.isAdd = false;
      this.form = this.$route.params.data;
      this.$route.meta.title = "选择题编辑";
    }
    //获取当前用户信息
    this.form.userId = JSON.parse(localStorage.getItem("user")).userId;
  },
  methods: {
    // 题目
    createTitle() {
      this.anotherForm.title = this.form.title;
      this.createTitleVisible = true;
      this.inputFocus();
    },
    sureCreateTitle() {
      this.form.title = this.anotherForm.title;
      this.createTitleVisible = false;
    },
    // 选项
    createOptions(index, prefix, content) {
      this.num = index;
      this.createOptionsVisible = true;
      this.anotherForm.answer.prefix = prefix;
      this.anotherForm.answer.content = content;
      this.inputFocus();
    },
    //使得dialog输入框获得焦点
    inputFocus() {
      this.$nextTick(() => {
        this.$refs.dialogInput.focus();
      });
    },
    addAnswer() {
      let items = this.form.answer;
      let newLastPrefix;
      if (items.length > 0) {
        let last = items[items.length - 1];
        newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1);
      } else {
        newLastPrefix = "A";
      }
      items.push({ prefix: newLastPrefix, content: "" });
    },
    sureCreateOptions() {
      this.form.answer[this.num].content = this.anotherForm.answer.content;
      this.createOptionsVisible = false;
      this.$refs.form.validateField("answer");
    },
    // 知识点
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.tags.push({
          name: inputValue,
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 提交
    retUpload() {
      this.UploadVisible = false;
      this.submitLoading = true;
      if (this.isAdd) {
        uploadSLProblem(this.form)
          .then((res) => {
            // alert("提交成功");
            this.$message.success("上传成功");
            this.$router.push({
              name: "questionModule/questionList",
              params: { mark: true },
            });
          })
          .finally(() => {
            this.submitLoading = false;
          });
      } else {
        delete this.form.indexId;
        delete this.form.removeLoading;
        editSLProblem(this.form)
          .then((res) => {
            this.$message.success("编辑成功");
            this.$router.push({
              name: "questionModule/questionList",
              params: { mark: true },
            });
          })
          .finally(() => {
            this.submitLoading = false;
          });
      }
    },
    //重置
    resetForm() {
      Object.assign(this.$data, this.$options.data());
    },
    upload() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.UploadVisible = true;
        }
      });
    },
  },
};
</script>

<style scoped>
.el-form-item {
  text-align: left;
  margin-bottom: 10px;
}
.title {
  width: 8.5rem;
}
.options {
  margin-bottom: 1px;
  width: 8.5rem;
}
.answer {
  margin-top: 15px;
}
.button-new-tag {
  margin: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
.cancel {
  margin-left: 450px;
}
</style>
